<template>
  <div class="page-container">
    <div class="control-container">
      <div class="left-panel shrink-panel" :class="isWide?'':'narrow'">
        <div class="shrink-btn-panel">
          <i :class="isWide?'el-icon-arrow-left':'el-icon-arrow-right'" @click="isWide = !isWide" />
        </div>
        <OutletTree
          v-if="isWide"
          ref="outletTree"
          @handleNodeClick="handleNodeClick"
        />
      </div>
      <div class="right-panel overflow-x">
        <div class="search-panel">
          <el-form :inline="true" label-width="default">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="query.startDate"
                class="width-142"
                type="date"
                placeholder="开始时间"
                value-format="yyyy-MM-dd"
                :clearable="false"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="query.endDate"
                class="width-142"
                type="date"
                placeholder="结束时间"
                value-format="yyyy-MM-dd"
                :clearable="false"
              />
            </el-form-item>
            <el-form-item label="行业类别">
              <el-select v-model="query.industryCategory" clearable class="width-142 " placeholder="请选择">
                <el-option
                  v-for="item in initCom.industryCategory"
                  :key="item.code"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="控制级别">
              <el-select v-model="query.controlLevel" clearable class="width-142" placeholder="请选择">
                <el-option
                  v-for="(item) in initCom.controlLevel"
                  :key="item.code"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="排放类型">
              <el-select v-model="query.emissionType" clearable class="width-142" placeholder="请选择">
                <el-option
                  v-for="item in initCom.emissionType"
                  :key="item.code"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="运维人员">
              <v-projectPersonnel
                ref="kll"
                @ch="ch"
              />
            </el-form-item>

            <el-form-item label="运维结果">
              <el-select v-model="query.maintenanceResults" clearable class="width-142" placeholder="请选择">
                <el-option
                  v-for="item in initCom.maintenanceResults"
                  :key="item.code"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select v-model="query.maintenanceStatus" multiple clearable placeholder="请选择">
                <el-option
                  v-for="(item,index) in statusList"
                  :key="index+'status_list'"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="表单类型">
              <el-select v-model="query.formType" clearable placeholder="请选择">
                <el-option
                  v-for="(item,index) in formTypes"
                  :key="index+'formType'"
                  :value="item.shortName"
                  :label="item.shortName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="">
              <div class="table-tools-bar">
                <el-button v-if="hasBtn('maintenance:list')" type="primary" @click="handleSelect">查询</el-button>
                <el-button v-if="hasBtn('maintenance:add')" type="primary" @click="handleAddForm">添加表单</el-button>
                <el-button v-if="hasBtn('maintenance:review')" type="primary" @click="handleCheck">审核</el-button>
                <el-button v-if="hasBtn('maintenance:confirm')" type="primary" @click="handleConfirm">确认</el-button>
                <el-button v-if="hasBtn('maintenance:submit')" type="primary" @click="handleSubmit">提交</el-button>
                <el-button v-if="hasBtn('maintenance:confirm')" type="primary" @click="handleOp">评价</el-button>
                <el-button v-if="hasBtn('maintenance:status')" type="primary" @click="updateStatus">修改状态</el-button>
                <el-button v-if="hasBtn('maintenance:download')" type="primary" @click="handleDownloadPic">下载图片</el-button>
                <el-button v-if="hasBtn('maintenance:download')" type="primary" @click="handleDownloadDoc">下载文档</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="table-panel">
          <el-table
            ref="multipleTable"
            v-loading="tableLoading"
            class="grid-data-table"
            height="calc(100vh - 420px)"
            :data="tableData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column align="center" type="selection" width="50" />
            <el-table-column prop="etpName" label="企业" show-overflow-tooltip width="120" />
            <el-table-column prop="outletName" label="排放口" width="120" />
            <el-table-column prop="equipmentTypeName" label="设备类型" width="120" />
            <el-table-column prop="outletChargeUsername" label="排口负责人" width="120" />
            <el-table-column prop="maintenanceUsername" label="运维人员" width="120" />
            <el-table-column prop="formNo" label="运维表单单号" show-overflow-tooltip width="180" />
            <el-table-column prop="maintenanceResultsName" label="运维结果" width="120" />
            <el-table-column prop="fillingFormTime" label="填表时间" show-overflow-tooltip width="160">
              <template slot-scope="scope">{{ parseTime(scope.row.fillingFormTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</template>
            </el-table-column>
            <el-table-column prop="maintenanceStatusName" label="状态" width="120" />
            <el-table-column prop="confirmedName" label="客户确认" width="120" />
            <el-table-column prop="checkOp" label="审批意见" width="120" />
            <el-table-column label="运维表单图" show-overflow-tooltip width="160">
              <template slot-scope="scope">
                <template v-for="(item,index) in scope.row['url'] ">
                  <el-image
                    :key="index + '_img'"
                    style="width: 25px; height: 25px"
                    :src="srcUrl"
                    :preview-src-list="previewSrc(scope.row['url'])"
                  />
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.maintenanceStatus === 'e016_01' && roleType !== 'e036_05' && roleType !== 'e036_06'"
                  class="table-inner-btn"
                  type="primary"
                  size="mini"
                  @click="handleEdit(scope.row)"
                >编辑
                </el-button>
                <el-button
                  v-if="scope.row.maintenanceStatus !== 'e016_01'"
                  class="table-inner-btn"
                  type="primary"
                  size="mini"
                  @click="handleDetail(scope.row)"
                >详情
                </el-button>
                <el-button
                  v-if="scope.row.maintenanceStatus === 'e016_01'||roleType == 'e036_01'"
                  class="table-inner-btn"
                  type="primary"
                  size="mini"
                  @click="handleDel(scope.row.id)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <Pagination
              v-show="query.total>0"
              :total="query.total"
              :page.sync="query.page"
              :limit.sync="query.limit"
              @pagination="initData"
            />
          </div>
        </div>
      </div>
    </div>
    <AddMaintenanceDialog
      :dialog-visible="dialog.add.visible"
      :dialog-type="dialog.add.dialogType"
      :obj="dialog.add.obj"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
    <EditMaintenanceDialog
      :dialog-visible="dialog.edit.visible"
      :dialog-type="dialog.edit.dialogType"
      :obj="dialog.edit.obj"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
    <CheckMaintenanceDialog
      :dialog-visible="dialog.check.visible"
      :dialog-type="dialog.check.dialogType"
      :obj="dialog.check.obj"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
    <ConfirmMaintenanceDialog
      :dialog-visible="dialog.confirm.visible"
      :dialog-type="dialog.confirm.dialogType"
      :obj="dialog.confirm.obj"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
    <MaintenanceDetailDialog
      :dialog-visible="maintenanceDetailVisible"
      :obj="dialog.edit.obj"
      :form-type="query.formType"
      @closeDialog="maintenanceDetailVisible = false"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getDict } from '@/utils/dict'
import {
  getPage,
  updateTMaintenance,
  downloadPic,
  updateMaintenanceStatus,
  del
} from '@/api/maintenanceManage/index'
import { downloadFile, parseTime } from '@/utils'
import AddMaintenanceDialog from './components/AddMaintenanceDialog'
import {
  getEnterprise, getDatefmt,
  getConfigureContent
} from '@/utils/common'
import { hasBtnPermission as hasBtn } from '@/utils/buttons'
import CheckMaintenanceDialog from '@/views/maintenanceManage/components/CheckMaintenanceDialog'
import ConfirmMaintenanceDialog from '@/views/maintenanceManage/components/ConfirmMaintenanceDialog'
import VProjectPersonnel from '@/components/filter/personnelFilter'
import { staticImgUrl } from '@/url'
import OutletTree from '@/components/Tree/outletTree'
import srcUrl from '@/assets/images/index/pic.png'
import EditMaintenanceDialog from './components/EditMaintenanceDialog'
import { getRoleType } from '@/utils/buttons'
import MaintenanceDetailDialog from './components/MaintenanceDetailDialog'
import { editEvaluation } from '@/api/maintenanceManage'
import { selectShortName } from '@/api/business/template'
export default {
  name: 'MaintenanceList',
  components: {
    AddMaintenanceDialog,
    EditMaintenanceDialog,
    Pagination,
    CheckMaintenanceDialog,
    ConfirmMaintenanceDialog,
    VProjectPersonnel,
    OutletTree,
    MaintenanceDetailDialog
  },
  data() {
    return {
      isWide: true,
      srcUrl,
      loginInfo: null,
      multipleSelection: [],
      tableLoading: false,
      query: {
        page: 1, limit: 10, total: 0,
        startDate: null, endDate: null, projectDepartmentId: null,
        enterpriseId: null, outletId: null, outletChargeId: null, emissionType: '', controlLevel: '',
        industryCategory: '', maintenanceResults: '', confirmed: '', maintenanceStatus: [], formType: null
      },
      initCom: {
        emissionType: [],
        controlLevel: [],
        industryCategory: [],
        maintenanceResults: [],
        confirmed: [],
        defultDateTime: null
      },
      tableData: [],
      outletChargeIdObj: {
        loading: false
      },
      dialog: {
        add: {
          visible: false,
          dialogType: 'detail',
          obj: null
        },
        edit: {
          visible: false,
          obj: null
        },
        check: {
          visible: false,
          dialogType: 'detail',
          obj: null
        },
        confirm: {
          visible: false,
          dialogType: 'detail',
          obj: null
        }
      },
      roleType: '',
      treeData: {
        projectDepartmentId: '',
        enterpriseId: '',
        outletId: ''
      },
      statusList: [],
      formTypes: [],
      ids: [],
      maintenanceDetailVisible: false
    }
  },
  created() {
    const info = this.$store.getters.user.info
    if (info) {
      if (typeof info === 'string') {
        this.loginInfo = JSON.parse(info)
      } else {
        this.loginInfo = info
      }
    }
    this.roleType = getRoleType()
    selectShortName().then(data => {
      this.formTypes = data.data.list
    })
    this.initCom.emissionType = getDict('e012')
    this.initCom.emissionType.unshift({ 'code': '', 'codeName': '全部' })
    this.initCom.controlLevel = getDict('e014')
    this.initCom.controlLevel.unshift({ 'code': '', 'codeName': '全部' })
    this.initCom.industryCategory = getDict('e013')
    this.initCom.industryCategory.unshift({ 'code': '', 'codeName': '全部' })
    this.initCom.maintenanceResults = getDict('e015')
    this.initCom.maintenanceResults.unshift({ 'code': '', 'codeName': '全部' })
    this.initCom.confirmed = getDict('e017')
    this.initCom.confirmed.unshift({ 'code': '', 'codeName': '全部' })
    this.statusList = getDict('e016')
    if (this.roleType === 'e036_04') {
      this.query.maintenanceStatus = ['e016_01']
    } else if (this.roleType === 'e036_03') {
      this.query.maintenanceStatus = ['e016_01', 'e016_02']
    }
    this.setDefaulTime()
    this.initData()
  },
  methods: {
    parseTime, hasBtn,
    previewSrc(list) {
      var urlArr = []
      list.forEach(item => {
        urlArr.push(staticImgUrl + item)
      })
      return urlArr
    },
    remoteMethodoutletChargeId(query) {
      const obj = this.outletChargeIdObj
      if (query !== '') {
        obj.loading = true
        getEnterprise(query).then(data => {
          obj.data = data.data.list
          obj.loading = false
        })
      } else {
        obj.data = []
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 表格选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    initData() {
      const query = JSON.parse(JSON.stringify(this.query))
      if (this.query.maintenanceStatus.length > 0) {
        query.maintenanceStatus = this.query.maintenanceStatus.join(',')
      }
      this.tableLoading = true
      getPage(query).then(result => {
        this.tableLoading = false
        this.query.total = result.data.page.total
        this.tableData = result.data.page.records
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 下载文档
    handleDownloadDoc() {

    },
    // 下载图片
    handleDownloadPic(status) {
      if (this.multipleSelection.length === 0) {
        this.$message('选择数据')
      } else {
        var query = ''
        for (let i = 0; i < this.multipleSelection.length; i++) {
          query = this.multipleSelection[i].id + ','
        }
        downloadPic({ 'id': query }).then(result => {
          downloadFile(result, '图片', 'zip')
        }).catch(() => {
          console.log('下载出问题')
        })
      }
    },
    // 添加表单
    handleAddForm() {
      this.dialog.add.obj = {
        projectDepartmentId: this.treeData.projectDepartmentId,
        enterpriseId: this.treeData.enterpriseId,
        outletId: this.query.outletId
      }
      this.dialog.add.visible = true
    },
    // 审核
    handleCheck(de, status) {
      const multipleSelection = this.multipleSelection
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[i].maintenanceStatus !== 'e016_02') {
          this.$message({
            message: '选中的数据已审核或不是待审核状态',
            type: 'warning'
          })
          return
        }
      }
      const id = []
      if (status == null) {
        if (multipleSelection.length === 0) {
          this.$message('请选择')
          return false
        } else {
          for (let i = 0; i < multipleSelection.length; i++) {
            id.push(multipleSelection[i].id)
          }
        }
      } else {
        id.push(status.id)
      }
      this.dialog.check.obj = { 'ids': id }
      this.dialog.check.visible = true
    },
    handleConfirm(status) {
      const multipleSelection = this.multipleSelection
      const id = []
      if (multipleSelection.length === 0) {
        this.$message('请选择')
        return false
      } else {
        for (let i = 0; i < multipleSelection.length; i++) {
          if (this.multipleSelection[i].maintenanceStatus === 'e016_01') {
            this.$message({
              message: '选中的数据中有运维工程师还未提交的数据',
              type: 'warning'
            })
            return false
          }
          if (this.multipleSelection[i].confirmed === 'e017_02') {
            this.$message({
              message: '选中的数据已确认',
              type: 'warning'
            })
            return false
          }
          // id.push(multipleSelection[i].id)
          id.push({ 'maintenanceId': multipleSelection[i].id,
            'op': 0
          })// 记录是否评价，0否，1是
        }
      }
      // this.dialog.confirm.obj = { 'ids': id, 'loginInfo': this.loginInfo }
      // this.dialog.confirm.visible = true
      editEvaluation(id).then((data) => {
        this.handleSelect()
        this.$message.success('成功')
      }).catch(() => {
        this.$message.error('失败')
      })
    },
    handleSubmit(detail, status) {
      const multipleSelection = this.multipleSelection
      const id = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[i].maintenanceStatus !== 'e016_01') {
          this.$message({
            message: '选中的数据已提交或不是已保存状态',
            type: 'warning'
          })
          return
        }
      }
      if (status == null) {
        if (multipleSelection.length === 0) {
          this.$message('请选择')
          return false
        } else {
          for (let i = 0; i < multipleSelection.length; i++) {
            id.push(multipleSelection[i].id)
          }
        }
      } else {
        id.push(status.id)
      }
      updateTMaintenance(id).then(result => {
        this.$alert('操作成功', '消息提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.initData()
          }
        })
      })
    },
    // 编辑
    handleEdit(row) {
      this.dialog.edit.obj = { 'ids': row.id }
      this.dialog.edit.visible = true
    },
    handleDel(id) {
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(() => {
          this.$message.success('成功')
          this.flushPage()
        }).catch(() => {
        })
      })
    },
    // 查询详情
    handleDetail(row) {
      this.dialog.edit.obj = row
      this.maintenanceDetailVisible = true
      // this.query = {
      //   ...this.query,
      //   startDate: null, endDate: null, responsible: null,
      //   taskStatus: null, taskType: null, taskName: null
      // }
    },
    // 评价
    handleOp() {
      console.log(this.multipleSelection)
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择')
      } else {
        const id = []
        this.multipleSelection.forEach(item => {
          id.push(item.id)
        })
        this.dialog.confirm.obj = { ids: id, loginInfo: this.loginInfo, doOp: '1' }
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].confirmed !== 'e017_02') {
            this.$message({
              message: '选中的数据未确认',
              type: 'warning'
            })
            return
          }
          if (this.multipleSelection[i].hasEvaluated !== 'e020_02') {
            this.$message({
              message: '选中的数据包含已评价',
              type: 'warning'
            })
            return
          }
        }
        this.dialog.confirm.visible = true
      }
    },
    // 修改提交后的状态
    updateStatus() {
      if (this.multipleSelection.length < 1) {
        this.$message.warning('请选择')
      } else {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].maintenanceStatus !== 'e016_02') {
            this.$message({
              message: '选中的数据不是待审核',
              type: 'warning'
            })
            return
          }
        }
        this.ids = []
        this.multipleSelection.forEach(value => {
          this.ids.push(value.id)
        })
        const maintenanceStatus = this.ids.join(',')
        this.$confirm('确认将选中的数据修改为已保存状态吗?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateMaintenanceStatus(maintenanceStatus).then(() => {
            this.$message.success('成功')
            this.flushPage()
          }).catch(() => {
          })
        })
      }
    },
    // 点击树
    handleNodeClick(data, node) {
      this.clearQuery()
      if (data.level === 1) {
        this.query.projectDepartmentId = data.id
        this.treeData.projectDepartmentId = data.id
      } else if (data.level === 2) {
        this.query.enterpriseId = this.treeData.enterpriseId = data.id
        this.treeData.projectDepartmentId = node.parent.data.id
      } else if (data.level === 3) {
        this.query.outletId = data.id
        this.treeData.enterpriseId = node.parent.data.id
        this.treeData.projectDepartmentId = node.parent.parent.data.id
      }
      this.initData()
    },
    // 查询
    handleSelect() {
      this.initData()
    },
    ch(id) { // 拿到v-projectPersonnel组键选择的人员id
      this.query.outletChargeId = id
    },
    // 添加
    handleAddOrDetail(dialogType, row) {
      this.dialogVisible = true
      this.dialogType = dialogType
      this.obj = row
    },
    // 查看图片
    handlePicGet(data) {
      // TODO
    },
    flushPage() {
      // this.clearQuery()
      this.initData()
    },
    // 设置默认时间条件
    setDefaulTime() {
      const date = new Date()
      const defaultTime = parseInt(getConfigureContent('e041_07'))
      this.query.startDate = getDatefmt(new Date(date.getTime() - 3600 * 1000 * 24 * defaultTime), 'yyyy-MM-dd')
      this.query.endDate = getDatefmt(date, 'yyyy-MM-dd')
    },
    // 清空查询条件
    clearQuery() {
      this.query = {
        ...this.query,
        page: 1, limit: 10, total: 0,
        projectDepartmentId: null,
        enterpriseId: null, outletId: null, outletChargeId: null
        // , emissionType: '', controlLevel: '', industryCategory: '', maintenanceResults: '', confirmed: ''
      }
      // this.setDefaulTime()
    },
    closeDialog() {
      this.dialog.edit.visible = false
      this.dialog.add.visible = false
      this.dialog.check.visible = false
      this.dialog.confirm.visible = false
    }
  }

}
</script>

<style lang="scss" scoped>
</style>
